from django.shortcuts import render
# from requests import request
# 定义装饰器  用来判断用户是否登录
from django.utils.decorators import method_decorator
# 定义login_requered
from django.contrib.auth.decorators import login_required
# 定义View
from django.views import View
# 引入area表addresses表
from addresses.models import Area,Address

from django.core.cache import cache
# 引入json返回类型
from django.http import JsonResponse
# 引入json模块
import json
# 引入re模块
import re

# -------------------省市区三级联动-----------------------

from addresses.models import Address

# 装饰器用来判断用户是否登录
@method_decorator(login_required,name = 'dispatch')
class AddressView(View):
    # 获取展示地址页面
    def get(self,request):
    # 查询当前用户的地收货地址信息
        # 获取用户信息
        user = request.user
        # 在数据库中查询当前地址的信息
        addresses = Address.objects.filter(user =user,is_deleted=False)
        # 创建列表，用来保存收回地址信息
        addresses_list = []
        # 遍历出收货地址
        for address in addresses:
            addresses_list.append({
                'id':address.id,
                # 接收器
                'receiver':address.receiver,
                # 省份
                'province':address.province.name,
                # 省份所对应的城市
                'city':address.city.name,
                # 城市所对应的地区
                'district':address.district.name,
                #
                'place':address.place,
                # 手机号
                'mobile':address.mobile,
                # tel
                'tel':address.tel,
                # 邮箱
                'email':address.email,
                #
                'title':address.title
            })

        return render(request,'user_center_site.html',{'addresses':addresses_list})
#--------------------填写收货地址的省市去信息-----------------------------
# 定义装饰器用来判断用户是否登录
@method_decorator(login_required,name='dispatch')
class AreasView(View):
    def get(self,request):
        '''
        获取省信息
        :param request:
        :return:
        '''
        # 获取area_id（在路径中会携带area_id数据）  area_id  是在获取到省id的时候会发送给后端
        area_id = request.GET.get('area_id')
        # 如果id为空获取的就是省的地址
        if area_id is None:
            # 在存储器中获取 省的数据
            province_list = cache.get('province_list')
            if province_list is None:
                # 获取省的信息
                data = Area.objects.filter(parent_id=area_id)
                province_list = []
                # 遍历出每个省的信息
                for province in data:
                    # 添加到provice_list列表中
                    province_list.append({
                        'id':province.id,
                        'name':province.name
                    })
                    # 讲provice_listzhong 中的数据保存在cache中
                    # cache市一个高数缓冲存储器
                cache.set('provience_list',province_list,60*60*2)
        else:
            # 获取id为area_id的省的市的信息
            # 在cache中获取保存的市或地区的信息
            province_list = cache.get('province_list_%s'%area_id)
            if province_list is None:
                # 获取对应的市或者地区的信息
                data = Area.objects.filter(parent_id=area_id)
                province_list = []
                for provice in data:
                    # 将数据添加到provice_list中
                    province_list.append({
                        'id':provice.id,
                        'name':provice.name
                    })
                    # 将数据保存在cache中
                cache.set('provience_list_%s'%area_id,province_list,60*60*2)
        return JsonResponse({
            'code':'0',
            'province_list':province_list
        })
# -------------------------------------保存收货地址-------------------------------------
class AddressCreateView(View):
    def post(self,request):
        '''
         # 保存收货地址
        :param request:
        :return:
        '''
        #获取json数据
        data = request.body.decode()
        # 对json数据进行解析，转化为字典类型
        data_dict = json.loads(data)
        # 获取前段的数据
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')
        # 2.验证数据
        if len(receiver) > 20 or len(receiver)<0:
            return JsonResponse({"code":5001})
        if not re.match(r'1[3-9]\d{9}',mobile):
            return JsonResponse({"code":4007})
        if mobile is None or mobile =='':
            return JsonResponse({"code":4007})
        user = request.user
        # 3.保存数据
        addresses = Address.objects.create(user = user,receiver=receiver, province_id=province_id, city_id=city_id,
                                         district_id=district_id, place=place, mobile=mobile, tel=tel, email=email)
        # 创建json数据，讲前端传入的数据写入json中
        address_dict  ={
            'id': addresses.id,
            # 接收器
            'receiver': addresses.receiver,
            # 省份
            'province': addresses.province.name,
            # 城市
            'city': addresses.city.name,
            # 地区
            'district': addresses.district.name,
            # 手机号
            'mobile': addresses.mobile,
            # tel
            'tel': addresses.tel,
            # 邮箱
            'email': addresses.email,
        }
        # 返回json数据
        return JsonResponse({'code':'0','address':address_dict})


#-------------------------更新地址---------------------------------
    def put(self,request,pk):
        # 1.获取前段页面数据
        data = request.body.decode()
        data_dict = json.loads(data)
        receiver = data_dict.get('receiver')
        province_id= data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')

        tel = data_dict.get('tel')
        email = data_dict.get('email')
        # 2.验证前端传入的数据
        # 验证用户名格式是否正确
        if len(receiver) > 20 or len(receiver) < 0:
            return JsonResponse({'code':5001})
        # 验证手机好格式是否正确
        if not re.match(r'1[3-9]\d{9}',mobile):
            return JsonResponse({'code':4007})
        # 验证手机号是否为空
        if mobile is None or mobile =='':
            return JsonResponse({'code':4007})
        # 3.更新数据
        # pk 是前段传入的数字，用来确认是哪个地址信息
        address = Address.objects.get(id=pk)
        address.receiver = receiver
        address.province_id = province_id
        address.city_id = city_id
        address.district_id = district_id
        address.place = place
        address.mobile = mobile
        address.tel = tel
        address.email = email
        address.save()

        # 4.返回结果
        # 获取数据库中修改后的数据放入字典中，用于json数据的返回
        address_dict = {
            'id': address.id,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }
        # 4、返回结果
        return JsonResponse({'code': '0', 'address': address_dict})
# -------------------------------删除数据----------------------
    def delete(self,request,pk):
        try:
            address = Address.objects.get(id=pk)
        except:
            return JsonResponse({"code":5001})
        # 2.删除守护地址
        address.is_deleted = True
        address.save()
        # 3.返回结果
        return JsonResponse({'code':0})
# ------------------------------默认地址----------------------
class AddressDefaultView(View):
    def put(self,request,pk):
        # 查询地址是否存在
        try:
            address = Address.objects.get(id = pk)
        except:
            return JsonResponse({'code':5001})
        # 将查询到的地址设为默认地址
        user = request.user
        user.default_address = address
        user.save()

        return JsonResponse({'code':0})
# ------------------------------设置标题----------------------
class AddressTitleView(View):
    def put(self,request,pk):
        try:
            address = Address.objects.get(id=pk)
        except:
            return JsonResponse({'code':5001})
        # 获取用户前端页面的标题
        title = json.loads(request.body.decode()).get('title')
        address.title = title
        address.save()
        # 返回结果
        return JsonResponse({'code':0})




























